import { Col, Form, Select, TreeSelect } from 'antd';
import { SearchComponApi } from './type';
import cls from 'classnames';
import { getUserDataList } from '../../hooks';
import { getDeptPosTreeIcon, loopArray } from '@/utils';
import { Fragment, useContext, useEffect, useMemo } from 'react';
import MyIcon from '@/components/MyIcon';
import deptUserStyles from '../../styles.less';
import { ManageContext } from '../../store';
import pageStyles from '@/common/pageLayout.less';

export const SearchDeptAndUserSelect: React.FC<SearchComponApi.IPropsType> = (props) => {
  let orgList: any = props?.opt?.dataSource;

  /** 获取上下文 */
  const { Search } = useContext(ManageContext);

  /**获取用户 接口 */
  const { getUserRun, getUserLoading, getUserList } = getUserDataList();

  let pageSize: any = {
    page: 1,
    rows: 10000,
  };

  useEffect(() => {
    if (props?.visible || !props?.opt?.whetherSenior) {
      defaultUser();
    }
  }, [props?.visible, props?.opt?.whetherSenior]);

  // 处理初始化渲染
  const defaultUser = () => {
    // let userFORM: string = props?.opt?.name;
    if (props?.opt?.whetherSenior) {
      let payload: any = {
        ...pageSize,
      };
      getUserRun(payload);

      // if (Search?.filterDrawerValues?.[userFORM]) {
      // onTreeChange(Search?.filterDrawerValues?.[userFORM])
      // } else {
      // onTreeChange(props?.opt?.dataSource?.[0]?.id)
      // }
    } else {
      let payload: any = {
        ...pageSize,
      };
      getUserRun(payload);
      // if (Search?.searchValues?.[userFORM]) {
      //   // onTreeChange(Search?.searchValues?.[userFORM])
      // } else {
      //   // onTreeChange(props?.opt?.dataSource?.[0]?.id)
      // }
    }
  };

  // 处理树数据
  const orgTreeData = (data: any[]): any[] => {
    return data?.map((item: any) => {
      // return (
      //   <TreeSelect.TreeNode
      //     value={item?.id}
      //     key={item?.id}
      //     children={
      //       item?.children && item?.children?.length > 0
      //         ? orgTreeData(item?.children)
      //         : null
      //     }
      //     title={
      //       <div key={`${item?.id}${Math.random()}`}>
      //         {getDeptPosTreeIcon(String(item?.textType))}
      //         {item?.text}
      //       </div>
      //     }
      //     searchTitle={item?.text}
      //     itemRef={{ ...item }}
      //     textType={item?.textType}
      //   />
      // );
      return {
        title: <div key={`${item?.id}${Math.random()}`}>{item?.text}</div>,
        value: item?.id,
        key: item?.id,
        children: item?.children && item?.children?.length > 0 ? orgTreeData(item?.children) : null,
        label: (
          <div title={item?.text} className={pageStyles['over-flow-hidden']}>
            {getDeptPosTreeIcon(String(item?.textType))}
            {item?.text}
          </div>
        ),
        searchTitle: item?.text,
        itemRef: { ...item },
        textType: item?.textType,
      };
    });
  };

  /**处理树选中后获取用户的参数
   * @param list 传入的选中书id
   * @returns
   */
  const handleGetId = (list: any[]) => {
    // let paramsIDS: any = []; //参数保存
    // let checkRow = list[0]; //点击选中的节点
    let paramsIds: any = {};
    let textTypeZero: string[] = []; //保存公司参数
    let textTypeOne: string[] = []; //保存部门参数
    let textTypeTwo: string[] = []; //保存岗位参数
    // 递归树
    let loop = (treeData: any[]) => {
      treeData?.forEach((item: any) => {
        if (item?.children && item?.children?.length > 0) {
          loop(item?.children);
        }
        if (item?.textType == 0) {
          textTypeZero?.push(item?.id);
        }
        if (item?.textType == 1) {
          textTypeOne?.push(item?.id);
        }
        if (item?.textType == 2) {
          textTypeTwo?.push(item?.id);
        }
      });
    };
    loop(list);
    // let idsString = paramsIDS?.join('|');
    if (textTypeTwo && textTypeTwo?.length > 0) {
      // return { userCompanyID: idsString };
      let idsString = textTypeTwo?.join('|');
      paramsIds['userPositionID'] = idsString;
    }
    if (textTypeOne && textTypeOne?.length > 0) {
      // return { userDepartmentID: idsString };
      let idsString = textTypeOne?.join('|');
      paramsIds['userDepartmentID'] = idsString;
    }
    if (textTypeZero && textTypeZero?.length > 0) {
      // return { userPositionID: idsString };
      let idsString = textTypeZero?.join('|');
      paramsIds['userCompanyID'] = idsString;
    }
    return paramsIds;
  };

  // 点击左侧树结构
  const onTreeChange = (selectedKeys: any, _selectedNodes?: any) => {
    let checkKeys: string[] = [];
    selectedKeys?.forEach((itemID: any) => {
      checkKeys?.push(itemID?.value);
    });
    let treeList = loopArray(orgList);
    let selectList = treeList?.filter((item: any) => checkKeys?.includes(item?.id));

    let userListPayload = { ...pageSize, ...handleGetId(selectList) };
    getUserRun(userListPayload);
  };

  /**处理 getUserList 改变*/
  const userListMemo = useMemo(() => {
    if (getUserList && getUserList?.length > 0) {
      return getUserList;
    } else {
      return [];
    }
  }, [getUserList]);

  /**主要为了解决性能,和处理初始化用户数据 */
  const treeListMemo = useMemo(() => {
    if (orgList && orgList?.length > 0) {
      return orgList;
    } else {
      return [];
    }
  }, [orgList]);

  /**
   * @param e  下拉框滚动方法
   */
  // const onPopupScroll = (e: any) => {
  //   let { target } = e;
  //   //当前滚动到的位置
  //   let start = target.scrollTop + target.offsetHeight;
  //   //最后的位置
  //   let ned = target.scrollHeight;
  //   //滚动底部
  //   if (target.scrollTop != 0 && (ned - 5 <= start || start + 5 > ned)) {
  //     //处理逻辑.....
  //   }
  // };

  //监听select 按键触发事件
  // const onInputKeyDown = (e: any) => {
  //   const tempVal = e.target.value;
  //   if (e.key == 'Enter') {
  //   }
  // };

  return (
    <Fragment key={props?.opt?.name + '-deptSelect'}>
      <Col
        md={props?.opt?.whetherSenior ? 24 : props?.opt?.md ? props?.opt?.md : 4}
        sm={props?.opt?.whetherSenior ? 24 : props?.opt?.sm ? props?.opt?.sm : 24}
        key={`${props?.opt?.name}${Math.random()}`}
      >
        <Form.Item
          style={{ ...props?.opt?.itemStyle }}
          name={props?.opt?.name + 'Dept'}
          label={props?.opt?.whetherSenior ? `${props?.opt?.label}组织` : ''}
          className={cls('drawer-form-item')}
        >
          <TreeSelect
            placeholder={`${props?.opt?.label}组织`}
            showSearch
            allowClear
            treeNodeFilterProp={'searchTitle'}
            treeData={orgTreeData(treeListMemo)}
            // onChange={onTreeChange}
            onDropdownVisibleChange={(open) => {
              if (!open && Search?.filterDrawerValues?.[`${props?.opt?.name}Dept`]?.length > 0) {
                onTreeChange(Search?.filterDrawerValues?.[`${props?.opt?.name}Dept`]);
              }
            }}
            loading={orgList?.length > 0 ? false : true}
            treeCheckable={true}
            treeCheckStrictly={true}
            showCheckedStrategy={TreeSelect.SHOW_ALL}
            maxTagCount={1}
            showArrow
            className={deptUserStyles['searchForm-treeSelect']}
            popupClassName={deptUserStyles['searchForm-treeSelect-popupClass']}
            fieldNames={props?.opt?.fieldNames ? props?.opt?.fieldNames : { label: 'label', value: 'value', children: 'children' }}
          >
            {/* {orgTreeData(treeListMemo)} */}
          </TreeSelect>
        </Form.Item>
      </Col>
      {!props?.opt?.isShowDept && (
        <Col
          md={props?.opt?.whetherSenior ? 24 : props?.opt?.md ? props?.opt?.md : 4}
          sm={props?.opt?.whetherSenior ? 24 : props?.opt?.sm ? props?.opt?.sm : 24}
          // key={props?.opt?.name + '-userSelect'}
          key={`${props?.opt?.name}${Math.random()}`}
        >
          <Form.Item
            style={{ ...props?.opt?.itemStyle }}
            // name={props?.opt?.formOrgType?.USER}
            name={props?.opt?.name + 'User'}
            label={props?.opt?.whetherSenior ? `${props?.opt?.label}人` : ''}
            className={cls('drawer-form-item')}
          >
            <Select
              placeholder={`${props?.opt?.label}人`}
              loading={getUserLoading}
              allowClear
              showSearch
              optionFilterProp={'searchtitle'}
              mode="multiple"
              showArrow
              maxTagCount={1}
              className={deptUserStyles['searchForm-treeSelect']}
              // onInputKeyDown={onInputKeyDown}
            >
              {userListMemo && userListMemo?.length > 0 ? (
                <>
                  {userListMemo?.map((item: any) => {
                    return (
                      <Select.Option
                        // disabled={item?.id == getUserID() ? true : false}
                        value={item?.id}
                        key={item?.id}
                        searchtitle={item?.realName}
                      >
                        <MyIcon style={{ marginRight: 5 }} type="icon-lianxiren" />
                        {item?.realName}
                      </Select.Option>
                    );
                  })}
                </>
              ) : (
                <></>
              )}
            </Select>
          </Form.Item>
        </Col>
      )}
      {/* <Form.Item
        name={props?.opt?.formOrgType?.COMP}
        label=""
        style={{ display: 'none' }}
      >
        <Input />
      </Form.Item>
      <Form.Item
        name={props?.opt?.formOrgType?.DEPT}
        label=""
        style={{ display: 'none' }}
      >
        <Input />
      </Form.Item>
      <Form.Item
        name={props?.opt?.formOrgType?.POS}
        label=""
        style={{ display: 'none' }}
      >
        <Input />
      </Form.Item>
      <Form.Item
        name={props?.opt?.formOrgType?.USER}
        label=""
        style={{ display: 'none' }}
      >
        <Input />
      </Form.Item> */}
    </Fragment>
  );
};
